package com.louis.iread.ui;

import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.louis.iread.R;
import com.louis.iread.adapter.NovelOpAdapter;
import com.louis.iread.adapter.NovelOpOption;
import com.louis.iread.adapter.ThemeAdapter;
import com.louis.iread.bean.Article;
import com.louis.iread.bean.Book;
import com.louis.iread.bean.BookMgr;
import com.louis.iread.bean.Config;
import com.louis.iread.event.EventType;
import com.louis.iread.event.ReadEvent;
import com.louis.iread.receiver.BatteryReceiver;
import com.louis.iread.skin.SkinMgr;
import com.louis.iread.utils.AppUtils;
import com.louis.iread.utils.ConstValue;
import com.louis.iread.utils.DbUtil;
import com.louis.iread.utils.Pagination;
import com.louis.iread.utils.ScreenUtils;
import com.louis.iread.utils.SimpleTask;
import com.louis.iread.utils.StatusBarCompat;
import com.louis.iread.utils.ThreadPool;
import com.yarolegovich.lovelydialog.LovelyChoiceDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


@ContentView(R.layout.activity_read)
public class ReadActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {

    private static final int SHOW_IN_VIEW = 0;
    private static final int SHOW_IN_PRE = 1;
    private static final int SHOW_IN_NEXT = 2;

    private BatteryReceiver mBatteryReceiver;

    @ViewInject(R.id.gvTheme)
    GridView gvTheme;

    //两页切换显示
    @ViewInject(R.id.first_page)
    TextView pageView1; //第一页

    @ViewInject(R.id.second_page)
    TextView pageView2; //第二页

    @ViewInject(R.id.article_title)
    TextView articleTitleView; //章节标题

    TextView currentPageView; //当前正在显示的pageview

    @ViewInject(R.id.page_switcher)
    ViewFlipper flipper;
    GestureDetector detector;
    Animation[] animations = new Animation[4];

    Pagination mPagination; //分页器
    String mCurrentArticleContent = "";   //当前章节内容
    int mPageIndex = 0;  //分页索引

    int mCurrentWordProgress;//当前章节阅读字数,下次从章节的此位置阅读
    int mArticleIndex = 0;   //章节列表索引
    List<Article> mArticleList;
    long mBookIndex = -1;
    Book book;
    Article mCurrentArticle;

    int screenWidth;

    List<String> mPages = new ArrayList<>(); //页面

    final int FLIP_DISTANCE = 50;   //滑动最小距离

    TextView introView;

    protected int statusBarColor = 0;
    protected View statusBarView = null;

    @ViewInject(R.id.rlBookReadRoot)
    RelativeLayout mRlBookReadRoot;

    @ViewInject(R.id.llBookReadBottom)
    LinearLayout mLlBookReadBottom; //底部菜单

    @ViewInject(R.id.llBookReadTop)
    LinearLayout mLlBookReadTop;    //顶部菜单

    @ViewInject(R.id.tvBookReadIntroduce)
    TextView mBookIntro; //简介

    @ViewInject(R.id.rlReadAaSet)
    LinearLayout rlReadAaSet;   //字体亮度背景设置

    @ViewInject(R.id.vBookReadMode)
    LinearLayout vBookReadMode;    //夜间模式切换按钮
    @ViewInject(R.id.ivReadMode)
    ImageView   ivReadMode;         //夜间模式图片
    @ViewInject(R.id.tvReadMode)
    TextView    tvReadMode;    //夜间模式文字

    @ViewInject(R.id.show_pre)
    TextView mShowPreView; //上一章

    @ViewInject(R.id.show_next)
    TextView mShowNextView; //下一章

    @ViewInject(R.id.vBookReadSettings)
    LinearLayout vBookReadSettings; //字体亮度背景设置

    @ViewInject(R.id.tvBookReadDownload)
    LinearLayout tvBookReadDownload; //章节缓存按钮

    @ViewInject(R.id.tvBookContents)
    LinearLayout tvBookContents;    //章节目录按钮
    private View decodeView;

    @ViewInject(R.id.seekbarLightness)
    SeekBar mBrightnessSeekbar; //亮度设置

    @ViewInject(R.id.seekbarFontSize)
    SeekBar mFontSizeSeekbar; //字体大小设置

    @ViewInject(R.id.seekbarLineSpaceSize)
    SeekBar mLineSpace; //行距

    @ViewInject(R.id.battery_image)
    ImageView mBatteryView; //电量图标

    @ViewInject(R.id.time_view)
    TextView mTimeView;

    @ViewInject(R.id.process_view)
    TextView mProcessView;

    @ViewInject(R.id.ivBack)
    ImageView mBackView;

    Timer mTimer;
    TimerTask mTimerTask;

    int mTextSize = Config.getTextSize();  //阅读文字大小

    boolean bIsTraditional; //是不是繁体中文环境

    List<String> themeList;

    ThemeAdapter gvAdapter;

    public void setFontSize(int textSize) {
        pageView1.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
        pageView2.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
        if (mTextSize != textSize) {
            Config.setTextSize(textSize);
            mTextSize = textSize;
        }
    }

    public void setLineSpace(int lineSpace) {
        pageView1.setLineSpacing(pageView1.getLineSpacingExtra(), (float)lineSpace/10.0f);
        pageView2.setLineSpacing(pageView1.getLineSpacingExtra(), (float)lineSpace/10.0f);
        Config.setLineSpace(lineSpace);
    }

    void Dump() {
        Log.i("mPageIndex", "==>"+ mPageIndex);
        Log.i("mArticleIndex", "==>" + mArticleIndex);
        Log.i("worProgress", "==>" + mCurrentWordProgress + "/" + mCurrentArticleContent.length());
        Log.i(mCurrentArticle.getTitle(), mCurrentArticleContent);
        int len = 0;
        for (int i = 0; i < mPages.size(); i++) {
            len = len + mPages.get(i).length();
            Log.i(i + "/" + mPages.get(i).length(), "len=" + len + mPages.get(i));
        }
    }

    protected void hideStatusBar() {
        WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setAttributes(attrs);
        if(statusBarView != null){
            statusBarView.setBackgroundColor(Color.TRANSPARENT);
        }
    }

    protected void showStatusBar() {
        WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setAttributes(attrs);
        if(statusBarView != null){
            statusBarView.setBackgroundColor(statusBarColor);
        }
    }

    protected void gone(final View... views) {
        if (views != null && views.length > 0) {
            for (View view : views) {
                if (view != null) {
                    view.setVisibility(View.GONE);
                }
            }
        }
    }

    protected void visible(final View... views) {
        if (views != null && views.length > 0) {
            for (View view : views) {
                if (view != null) {
                    view.setVisibility(View.VISIBLE);
                }
            }
        }

    }

    protected boolean isVisible(View view) {
        return view.getVisibility() == View.VISIBLE;
    }

    private synchronized void hideReadBar() {
        gone(mLlBookReadBottom, mLlBookReadTop, rlReadAaSet);
        hideStatusBar();
        decodeView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
    }

    private synchronized void showReadBar() { // 显示工具栏
        visible(mLlBookReadBottom, mLlBookReadTop);
        showStatusBar();
        decodeView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    }

    private void toggleReadBar() { // 切换工具栏 隐藏/显示 状态
        if (isVisible(mLlBookReadTop)) {
            hideReadBar();
        } else {
            showReadBar();
        }
    }

    @Override
    public void onBackPressed() {
        if (isVisible(mLlBookReadBottom)) {
            hideReadBar();
        } else {
            super.onBackPressed();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgEvent(ReadEvent event) {
        switch (event.getEventType()) {
            case SWTCH_TO_DAY:
                ivReadMode.setImageResource(R.drawable.light_off);
                tvReadMode.setText(R.string.book_read_mode_night);
                String color = Config.getReadBg();
                mRlBookReadRoot.setBackgroundColor(ContextCompat.getColor(this, AppUtils.getColorId("read_theme_"+color)));
                break;
            case SWITCH_TO_NIGHT:
                ivReadMode.setImageResource(R.drawable.light_on);
                tvReadMode.setText(R.string.book_read_mode_day);
                break;
            case BATTERY_NTF:
                resetBatteryView(event.getValue());
                break;
            case UPDATE_TIME_NTF:
                resetTimeView();
                break;
            default:
                break;
        }
    }

    private void startTimer(){
        if (mTimer == null) {
            mTimer = new Timer();
        }

        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    EventBus.getDefault().post(new ReadEvent(EventType.UPDATE_TIME_NTF));
                }
            };
        }

        if(mTimer != null && mTimerTask != null )
            mTimer.schedule(mTimerTask, 0, 30 * 1000); //30s更新一次时间

    }

    private void stopTimer(){
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }

    public void resetProcessView() {
        String text = Integer.toString(mArticleIndex + 1) + "/" + Integer.toString(mArticleList.size());
        mProcessView.setText(text);
    }

    public void resetTimeView() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
        String timeStr = simpleDateFormat.format(new Date());
        mTimeView.setText(timeStr);
    }

    public void resetBatteryView(int power) {
        LayerDrawable layerDrawable = (LayerDrawable) mBatteryView.getDrawable();
        ClipDrawable clipDrawable = (ClipDrawable) layerDrawable.findDrawableByLayerId(R.id.clip_drawable);
        clipDrawable.setLevel(calculateLevel(power));
    }

    // 根据自己的电池图标精确计算裁剪区域
    private int calculateLevel(int progress) {
        int leftOffest = ScreenUtils.dpToPxInt(2);
        int powerLength = ScreenUtils.dpToPxInt(26.5f);// 40 px in hdpi
        int totalLength = ScreenUtils.dpToPxInt(32.5f);// 49 px in hdpi
        int level = (leftOffest + powerLength * progress / 100) * 10000 / totalLength;
        return level;
    }

    protected void initReadModeView() {
        String theme = Config.getTheme();
        if (Config.NIGHT.equals(theme)) {
            ivReadMode.setImageResource(R.drawable.light_on);
            tvReadMode.setText(R.string.book_read_mode_day);
        } else {
            ivReadMode.setImageResource(R.drawable.light_off);
            tvReadMode.setText(R.string.book_read_mode_night);
        }
    }

    void initViews() {
        statusBarColor = ContextCompat.getColor(this, R.color.reader_menu_bg_color);
        if (statusBarColor == 0) {
            statusBarView = StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.colorPrimaryDark));
        } else if (statusBarColor != -1) {
            statusBarView = StatusBarCompat.compat(this, statusBarColor);
        }

        mBackView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        decodeView = getWindow().getDecorView();
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mLlBookReadTop.getLayoutParams();
        params.topMargin = ScreenUtils.getStatusBarHeight(this) - 2;
        mLlBookReadTop.setLayoutParams(params);
        //手势
        detector = new GestureDetector(this, this);

        screenWidth = ScreenUtils.getScreenWidth();
        vBookReadMode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SkinMgr.getInstance().switchReadMode();
                String theme = Config.getTheme();
                if (theme.equals(Config.NIGHT)) {
                    gvAdapter.select(Config.NIGHT);
                    return;
                }
                String readBg = Config.getReadBg();
                gvAdapter.select(readBg);
            }
        });
        themeList = Arrays.asList(getResources().getStringArray(R.array.theme_list));

        String readThemeColor = Config.getReadBg();
        String theme = Config.getTheme();
        int selected = 0;

        int nightPos = 0;

        for (int i = 0; i < themeList.size(); i++) {
            if (readThemeColor.equals(themeList.get(i))) {
                selected = i;
            }
            if (Config.NIGHT.equals(themeList.get(i))) {
                nightPos = i;
            }
        }

        if (Config.NIGHT.equals(theme)) {
            selected = nightPos;
        } else {
            mRlBookReadRoot.post(new Runnable() {
                @Override
                public void run() {
                    int colorId = AppUtils.getColorId("read_theme_"+readThemeColor);
                    mRlBookReadRoot.setBackgroundColor(ContextCompat.getColor(ReadActivity.this, colorId));
                }
            });
        }

        gvAdapter = new ThemeAdapter(this, R.layout.item_read_theme, themeList, selected);
        gvTheme.setAdapter(gvAdapter);
        gvTheme.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String color = (String) gvAdapter.getItem(position);
                int colorId = AppUtils.getColorId("read_theme_"+color);

                gvAdapter.select(position);
                String theme = Config.getTheme();

                //当前为夜间模式
                if (theme.equals(Config.NIGHT)) {
                    if (color.equals(Config.NIGHT)) {
                        return;
                    }

                    Config.setReadBg(color);
                    SkinMgr.getInstance().switchReadMode();
                    mRlBookReadRoot.setBackgroundColor(ContextCompat.getColor(ReadActivity.this, colorId));
                } else { //当前为日间模式
                    //切换夜间模式
                    if (color.equals(Config.NIGHT)) {
                        SkinMgr.getInstance().switchReadMode();
                        return;
                    }

                    Config.setReadBg(color);
                    mRlBookReadRoot.setBackgroundColor(ContextCompat.getColor(ReadActivity.this, colorId));
                }
            }
        });
        tvBookContents.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleReadBar();
                Intent intent = new Intent(getApplicationContext(), ArticleListActivity.class);
                intent.putExtra(ConstValue.BOOK_INDEX, mBookIndex);
                intent.putExtra(ConstValue.ARTICLE_INDEX, mArticleIndex);
                startActivityForResult(intent, ConstValue.OPEN_ARTICLE_LIST_REQ);
            }
        });
        mBookIntro.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), NovelInfoActivity.class);
                intent.putExtra(ConstValue.BOOK_INDEX, mBookIndex);
                intent.putExtra(ConstValue.IS_READING, true);
                startActivity(intent);
            }
        });
        mShowPreView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int articleIndex = mArticleIndex - 1;
                if (articleIndex < 0) {
                    Toast.makeText(v.getContext(), R.string.current_is_first_article, Toast.LENGTH_SHORT).show();
                    return;
                }
                showArticle(articleIndex);
            }
        });
        mShowNextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int articleIndex = mArticleIndex + 1;
                if (articleIndex >= mArticleList.size()) {
                    Toast.makeText(v.getContext(), R.string.current_is_last_article, Toast.LENGTH_SHORT).show();
                    return;
                }
                showArticle(articleIndex);
            }
        });
        vBookReadSettings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (rlReadAaSet.isShown()) {
                    rlReadAaSet.setVisibility(View.GONE);
                } else {
                    rlReadAaSet.setVisibility(View.VISIBLE);
                }
            }
        });
        tvBookReadDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDowloadChoiceDialog();
            }
        });
        mBrightnessSeekbar.setProgress((int) ScreenUtils.getScreenBrightness(this.getApplicationContext()));
        mBrightnessSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                ScreenUtils.setScreenBrightness(progress, ReadActivity.this);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        mFontSizeSeekbar.setProgress(mTextSize);
        mFontSizeSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (progress < Config.MIN_TEXT_SIZE) {
                    setFontSize(Config.MIN_TEXT_SIZE);
                    seekBar.setProgress(Config.MIN_TEXT_SIZE);
                } else if (progress > Config.MAX_TEXT_SIZE) {
                    setFontSize(Config.MAX_TEXT_SIZE);
                    seekBar.setProgress(Config.MAX_TEXT_SIZE);
                } else  {
                    setFontSize(progress);
                }
                reShow();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        mLineSpace.setProgress(Config.getLineSpace());
        mLineSpace.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                setLineSpace(progress);
                reShow();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        initReadModeView();
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 根据上面发送过去的请求吗来区别
        switch (resultCode) {
            case ConstValue.OPEN_ARTICLE_LIST_ACK: {
                int articleIndex = data.getIntExtra("article_index", mArticleIndex);
                if (articleIndex == mArticleIndex) {
                    return;
                }
                showArticle(articleIndex);
            }
                break;
            default:
                break;
        }
    }

    protected void initAnimations() {
        animations[0] = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
        animations[1] = AnimationUtils.loadAnimation(this, R.anim.push_left_out);
        animations[2] = AnimationUtils.loadAnimation(this, R.anim.push_right_in);
        animations[3] = AnimationUtils.loadAnimation(this, R.anim.push_right_out);
    }

    protected void initBook() {
        Intent intent = getIntent();
        mBookIndex = intent.getLongExtra(ConstValue.BOOK_INDEX, -1);
        if (mBookIndex == -1) {
            finish();
            return;
        }
        book = BookMgr.getMgr().getBook(mBookIndex);
        if (book == null) {
            finish();
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String readTime = dateFormat.format(new Date());
        book.setReadTime(readTime);
        book.setUpdateTag(false);
        if (!book.isRead()) {
            book.setRead(true);
            try {
                DbUtil.getDbManager().saveOrUpdate(book);
            } catch (DbException e) {
                e.printStackTrace();
            }
        }

        //如果获取章节目录失败,则退出
        try {
            mArticleList = book.getArticles();
        } catch (DbException e) {
            e.printStackTrace();
            Toast.makeText(this, R.string.get_contents_failed, Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    protected void initPagination() {
        pageView1.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // Removing layout listener to avoid multiple calls
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                    pageView1.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    pageView1.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
                mPagination = new Pagination(
                        pageView1.getWidth(),
                        pageView1.getHeight(),
                        pageView1.getPaint(),
                        (float) Config.getLineSpace()/10.0f,
                        pageView1.getLineSpacingExtra(),
                        pageView1.getIncludeFontPadding());
                currentPageView = pageView1;
                beginShow();
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        SkinMgr.getInstance().register(this);
        initViews();
        setFontSize(mTextSize);
        initAnimations();
        initBook();
        initPagination();
        EventBus.getDefault().register(this);

        bIsTraditional = (this.getResources().getConfiguration().locale.getCountry().equals("TW") | this.getResources().getConfiguration().locale.getCountry().equals("HK"));

        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        mBatteryReceiver = new BatteryReceiver();
        registerReceiver(mBatteryReceiver, filter);
        startTimer();
    }

    private void reShow() {
        mPagination = new Pagination(
                pageView1.getWidth(),
                pageView1.getHeight(),
                pageView1.getPaint(),
                (float)Config.getLineSpace()/10.0f,
                pageView1.getLineSpacingExtra(),
                pageView1.getIncludeFontPadding());
        beginShow();
    }

    //activity打开开始显示
    private void beginShow() {
        mArticleIndex = book.getReadingArticleIndex();
        mCurrentArticle = mArticleList.get(mArticleIndex);
        mCurrentWordProgress = book.getReadingArticleWordNum();
        pageView1.setLineSpacing(pageView1.getLineSpacingExtra(), (float)Config.getLineSpace()/10.0f);
        pageView2.setLineSpacing(pageView1.getLineSpacingExtra(), (float)Config.getLineSpace()/10.0f);
        resetProcessView();
        if (!mCurrentArticle.isDownload()) {
            new SimpleTask(ReadActivity.this, true) {

                @Override
                public void doOnPreExe() {

                }

                @Override
                public void doOnPublish(Object ojb) {

                }

                @Override
                public Integer doOnBackgroundExe() {
                    boolean ret = downloadArticleContent(mCurrentArticle);
                    if (!ret) {
                        return -1;
                    }

                    return 1;
                }

                @Override
                public void doOnComplete(Integer result) {
                    if (result < 0) {
                        Toast.makeText(ReadActivity.this, R.string.download_failed, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    reSplitPages();
                    articleTitleView.setText(mCurrentArticle.getTitle());
                    showInView(SHOW_IN_VIEW, mPages.get(mPageIndex));
                }
            }.execute();
        } else {
            reSplitPages();
            articleTitleView.setText(mCurrentArticle.getTitle());
            showInView(SHOW_IN_VIEW, mPages.get(mPageIndex));
        }
    }

    void showDowloadChoiceDialog() {
        List<NovelOpOption> opOptionList = new ArrayList<NovelOpOption>();
        opOptionList.add(new NovelOpOption(R.string.download_50));
        opOptionList.add(new NovelOpOption(R.string.download_remainder_all));
        ArrayAdapter<NovelOpOption> novelOpOptionArrayAdapter = new NovelOpAdapter(this, opOptionList);
        new LovelyChoiceDialog(this)
                .setTitle(R.string.book_read_download)
                .setIcon(R.drawable.ic_star_border_white_36dp)
                .setItems( novelOpOptionArrayAdapter, new LovelyChoiceDialog.OnItemSelectedListener<NovelOpOption>() {
                    @Override
                    public void onItemSelected(int position, NovelOpOption item) {
                        if (item.strId == R.string.download_50) {
                            ThreadPool.getInstance().commit(new Runnable() {
                                @Override
                                public void run() {
                                    for (int i = mArticleIndex; i < mArticleList.size(); i++) {
                                        Article article = mArticleList.get(i);
                                        if (!article.isDownload())
                                            downloadArticleContent(article);

                                        if (i - mArticleIndex >= 50) {
                                            return;
                                        }
                                    }
                                }
                            });
                        } else if (item.strId == R.string.download_remainder_all) {
                            ThreadPool.getInstance().commit(new Runnable() {
                                @Override
                                public void run() {
                                    for (int i = mArticleIndex; i < mArticleList.size(); i++) {
                                        Article article = mArticleList.get(i);
                                        if (!article.isDownload())
                                            downloadArticleContent(article);
                                    }
                                }
                            });
                        }
                    }
                })
                .show();

    }

    void showArticle(final int articleIndex) {
        if (articleIndex < 0 || articleIndex >= mArticleList.size()) {
            return;
        }

        final Article article = mArticleList.get(articleIndex);
//        articleTitleView.setText(article.getTitle());
        //如果当前章节未下载,则进行下载
        if (!article.isDownload()) {
            new SimpleTask(ReadActivity.this, true) {

                @Override
                public void doOnPreExe() {

                }

                @Override
                public void doOnPublish(Object ojb) {

                }

                @Override
                public Integer doOnBackgroundExe() {
                    boolean ret = downloadArticleContent(article);
                    if (!ret) {
                        return -1;
                    }
                    return 1;
                }

                @Override
                public void doOnComplete(Integer result) {
                    if (result < 0) {
                        Toast.makeText(ReadActivity.this, R.string.download_failed, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    //下载成功后分页显示
                    mArticleIndex = articleIndex;
                    mCurrentArticle = article;
                    mCurrentArticleContent = book.getArticleContent(article, bIsTraditional);
                    mPages = mPagination.SplitPages(mCurrentArticleContent);
                    mPageIndex = 0;
                    mCurrentWordProgress = 0;
                    articleTitleView.setText(article.getTitle());
                    showInView(SHOW_IN_VIEW, mPages.get(mPageIndex));
                    preLoad();
                }
            }.execute();
        } else {
            mArticleIndex = articleIndex;
            mCurrentArticle = article;
            mCurrentArticleContent = book.getArticleContent(mCurrentArticle, bIsTraditional);
            mPages = mPagination.SplitPages(mCurrentArticleContent);
            mPageIndex = 0;
            mCurrentWordProgress = 0;
            articleTitleView.setText(article.getTitle());
            showInView(SHOW_IN_VIEW, mPages.get(mPageIndex));
            preLoad();
        }

    }

    //根据章节内的阅读进度对章节分页
    private void reSplitPages() {
        mCurrentArticleContent = book.getArticleContent(mCurrentArticle, bIsTraditional);
        if (mCurrentArticleContent == null || mCurrentArticleContent.length() == 0) {
            return;
        }
        Log.i("progress", mCurrentWordProgress + "/" + mCurrentArticleContent.length());
        if (mCurrentWordProgress < 0 || mCurrentWordProgress >= mCurrentArticleContent.length() - 1) {
            mCurrentWordProgress = 0;
        }
        if (mCurrentWordProgress == 0) {
            mPages = mPagination.SplitPages(mCurrentArticleContent);
            return;
        }
        //把章节中进度前和进度后的内容分别分页
        String before = mCurrentArticleContent.substring(0, mCurrentWordProgress);
        mPages = mPagination.SplitPages(before);

        mPageIndex = mPages.size();
        String after = mCurrentArticleContent.substring(mCurrentWordProgress, mCurrentArticleContent.length());
        List<String> afterPages = mPagination.SplitPages(after);
        for (String page : afterPages) {
            mPages.add(page);
        }
    }

    //下载章节内容
    private boolean downloadArticleContent(Article article) {
        if (article == null) {
            return false;
        }
        if (!article.isDownload()) {
            return forceDownloadArticleContent(article);
        }
        return true;
    }

    //强制重新下载
    private boolean forceDownloadArticleContent(Article article) {
        if (article == null) {
            return false;
        }
        return book.downloadArticleContent(article);
    }

    private void preLoad() {
        final int preLoadNum = Config.getPreLoad();
        for (int i = mArticleIndex; i < mArticleList.size(); i++) {
            Article article = mArticleList.get(i);
            if (!article.isDownload())
                break;

            if (i - mArticleIndex >= preLoadNum) {
                return;
            }
        }

        ThreadPool.getInstance().commit(new Runnable() {
            @Override
            public void run() {
                for (int i = mArticleIndex; i < mArticleList.size(); i++) {
                    Article article = mArticleList.get(i);
                    if (!article.isDownload())
                        downloadArticleContent(article);

                    if (i - mArticleIndex >= preLoadNum) {
                        return;
                    }
                }
            }
        });
    }

    public boolean onTouchEvent(MotionEvent event) {
        return detector.onTouchEvent(event);
    }

    @Override
    public boolean onDown(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent motionEvent) {
        float x = motionEvent.getX();

        Log.i("x", x + "/" + screenWidth);

        if (x > (screenWidth * 2 / 3)) {
            if (isVisible(mLlBookReadTop)) {
                hideReadBar();
            }
            showNext();
        } else if (x < (screenWidth / 3)) {
            if (isVisible(mLlBookReadTop)) {
                hideReadBar();
            }
            showPre();
        } else {
            //菜单
            toggleReadBar();
        }

        //显示菜单
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent motionEvent) {

    }

    //显示前一页
    public void showPre() {
        //如果当前显示的是本章第0页,则需要对前一章分页
        if (mPageIndex == 0) {
            //如果当前章节是起始章节,则需要提示
            if (mArticleIndex == 0) {
                Toast.makeText(ReadActivity.this, R.string.current_is_first_article, Toast.LENGTH_SHORT).show();
                return;
            }
            //进度调节到前一章
            final int articleIndex = mArticleIndex -1;
            final Article article = mArticleList.get(articleIndex);
            //如果当前章节未下载,则进行下载
            if (!article.isDownload()) {
                new SimpleTask(ReadActivity.this, true) {

                    @Override
                    public void doOnPreExe() {

                    }

                    @Override
                    public void doOnPublish(Object ojb) {

                    }

                    @Override
                    public Integer doOnBackgroundExe() {
                        boolean ret = downloadArticleContent(article);
                        if (!ret) {
                            return -1;
                        }
                        return 1;
                    }

                    @Override
                    public void doOnComplete(Integer result) {
                        if (result < 0) {
                            Toast.makeText(ReadActivity.this, R.string.download_failed, Toast.LENGTH_SHORT).show();
                            return;
                        }
                        //下载成功后分页显示
                        mArticleIndex = articleIndex;
                        mCurrentArticle = article;
                        mCurrentArticleContent = book.getArticleContent(article, bIsTraditional);
                        mPages = mPagination.SplitPages(mCurrentArticleContent);
                        mPageIndex = mPages.size() - 1;
                        mCurrentWordProgress = mCurrentArticleContent.length() - mPages.get(mPageIndex).length();
                        articleTitleView.setText(mCurrentArticle.getTitle());
                        showInView(SHOW_IN_PRE, mPages.get(mPageIndex));
                    }
                }.execute();
            } else {
                mArticleIndex = articleIndex;
                mCurrentArticle = article;
                mCurrentArticleContent = book.getArticleContent(mCurrentArticle, bIsTraditional);
                mPages = mPagination.SplitPages(mCurrentArticleContent);
                mPageIndex = mPages.size() - 1;
                mCurrentWordProgress = mCurrentArticleContent.length() - mPages.get(mPageIndex).length();
                articleTitleView.setText(mCurrentArticle.getTitle());
                showInView(SHOW_IN_PRE, mPages.get(mPageIndex));
            }
        } else {
            mPageIndex--;
            mCurrentWordProgress = mCurrentWordProgress - mPages.get(mPageIndex).length();
            showInView(SHOW_IN_PRE, mPages.get(mPageIndex));
        }
    }

    public void showInView(int showInWhere, CharSequence text) {
        if (text == null) {
            return;
        }
        if (showInWhere == SHOW_IN_PRE) {
            if (Config.PAGE_SLIDE.equals(Config.getPageMethod())) {
                this.flipper.setInAnimation(AnimationUtils.loadAnimation(this,
                        R.anim.push_right_in));
                this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
                        R.anim.push_right_out));
            }
            if (currentPageView == pageView1) {
                currentPageView = pageView2;
            } else {
                currentPageView = pageView1;
            }
            currentPageView.setText(text);
            flipper.showPrevious();
        } else if (showInWhere == SHOW_IN_NEXT){
            if (Config.PAGE_SLIDE.equals(Config.getPageMethod())) {
                this.flipper.setInAnimation(AnimationUtils.loadAnimation(this,
                        R.anim.push_left_in));
                this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
                        R.anim.push_left_out));
            }
            if (currentPageView == pageView1) {
                currentPageView = pageView2;
            } else {
                currentPageView = pageView1;
            }
            currentPageView.setText(text);
            flipper.showNext();
        } else if (showInWhere == SHOW_IN_VIEW) {
            currentPageView.setText(text);
        }
        setCurrentProgress();
        resetProcessView();
//        preLoad();
    }

    private void setCurrentProgress() {
        //修改小说读状态
        if (!mCurrentArticle.isRead()) {
            mCurrentArticle.setRead(true);
            try {
                DbUtil.getDbManager().saveOrUpdate(mCurrentArticle);
            } catch (DbException e) {
                e.printStackTrace();
            }
        }

        //修改小说进度
        book.setReadingArticleIndex(mArticleIndex);
        book.setReadingArticleWordNum(mCurrentWordProgress);
        try {
            DbUtil.getDbManager().saveOrUpdate(book);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }


    //显示后一页
    private void showNext() {
        //最后一页
        if (mPageIndex == mPages.size() - 1) {
            //最后一章
            if (mArticleIndex == mArticleList.size() - 1) {
                Toast.makeText(ReadActivity.this, R.string.current_is_last_article, Toast.LENGTH_SHORT).show();
                return;
            }
            preLoad();
            //进度调节到下一章
            final int articleIndex = mArticleIndex + 1;
            final Article article = mArticleList.get(articleIndex);
            //如果当前章节未下载,则进行下载
            if (!article.isDownload()) {
                new SimpleTask(ReadActivity.this, true) {

                    @Override
                    public void doOnPreExe() {

                    }

                    @Override
                    public void doOnPublish(Object ojb) {

                    }

                    @Override
                    public Integer doOnBackgroundExe() {
                        boolean ret = downloadArticleContent(article);
                        if (!ret) {
                            return -1;
                        }
                        return 1;
                    }

                    @Override
                    public void doOnComplete(Integer result) {
                        if (result < 0) {
                            Toast.makeText(ReadActivity.this, R.string.download_failed, Toast.LENGTH_SHORT).show();
                            return;
                        }
                        //下载成功后分页显示
                        mArticleIndex = articleIndex;
                        mCurrentArticle = article;
                        mCurrentArticleContent = book.getArticleContent(mCurrentArticle, bIsTraditional);
                        mPages = mPagination.SplitPages(mCurrentArticleContent);
                        mPageIndex = 0;
                        mCurrentWordProgress = 0;
                        articleTitleView.setText(mCurrentArticle.getTitle());
                        showInView(SHOW_IN_NEXT, mPages.get(mPageIndex));
                    }
                }.execute();
            } else {
                mArticleIndex = articleIndex;
                mCurrentArticle = article;
                mCurrentArticleContent = book.getArticleContent(mCurrentArticle, bIsTraditional);
                mPages = mPagination.SplitPages(mCurrentArticleContent);
                mPageIndex = 0;
                mCurrentWordProgress = 0;
                articleTitleView.setText(mCurrentArticle.getTitle());
                showInView(SHOW_IN_NEXT, mPages.get(mPageIndex));
            }
        } else {
            mCurrentWordProgress = mCurrentWordProgress + mPages.get(mPageIndex).length();
            mPageIndex++;
//            articleTitleView.setText(mCurrentArticle.getTitle());
            showInView(SHOW_IN_NEXT, mPages.get(mPageIndex));
        }
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float v, float v1) {
        if (e1.getX() - e2.getX() > 120) {
            showNext();
            return true;
        } else if (e1.getX() - e2.getX() < -120) {
            showPre();
            return true;
        }
        return false;
    }


    //退出当前Activity时被调用,调用之后Activity就结束了
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().post(new ReadEvent(EventType.UPDATE_BOOK_LIST));
        SkinMgr.getInstance().unregister(this);
        EventBus.getDefault().unregister(this);
        unregisterReceiver(mBatteryReceiver);
        stopTimer();
    }

}
